﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace george.Web.Helper {
    /// <summary>
    /// IP地址处理类
    /// </summary>
    public static class IpAddressHelper {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="ipAddress"></param>
        /// <returns></returns>
        public static int IpAddressV4ToInt(string ipAddress){
            if(IsIpAddressV4(ipAddress)==false)
                throw new Exception("不是有效的IPV4地址：" + ipAddress);
            var items = ipAddress.Split(new char[] { '.' });
            if (items.Length != 4){
                throw new Exception("不是有效的IPV4地址：" + ipAddress);
            }
            var ip = IPAddress.Parse(ipAddress);
            var bytes = ip.GetAddressBytes();
            return bytes[0] << 24
                   | bytes[1] << 16
                   | bytes[2] << 8
                   | bytes[3];
        }
        
        /// <summary>
        /// 是否IP（IPV4）地址
        /// </summary>
        /// <param name="ipAddress"></param>
        /// <returns></returns>
        public static bool IsIpAddressV4(string ipAddress){
            if (string.IsNullOrWhiteSpace(ipAddress)) return false;
            ipAddress = ipAddress.Trim();
            var ipv4Reg = new Regex("^((?:(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d)))\\.){3}(?:25[0-5]|2[0-4]\\d|((1\\d{2})|([1-9]?\\d))))$", RegexOptions.Compiled);
            if (ipv4Reg.IsMatch(ipAddress))
                return true;
            //var ipv6Reg = new Regex("^([\\da-fA-F]{1,4}:){6}((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$|^::([\\da-fA-F]{1,4}:){0,4}((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$|^([\\da-fA-F]{1,4}:):([\\da-fA-F]{1,4}:){0,3}((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$|^([\\da-fA-F]{1,4}:){2}:([\\da-fA-F]{1,4}:){0,2}((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$|^([\\da-fA-F]{1,4}:){3}:([\\da-fA-F]{1,4}:){0,1}((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$|^([\\da-fA-F]{1,4}:){4}:((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)$|^([\\da-fA-F]{1,4}:){7}[\\da-fA-F]{1,4}$|^:((:[\\da-fA-F]{1,4}){1,6}|:)$|^[\\da-fA-F]{1,4}:((:[\\da-fA-F]{1,4}){1,5}|:)$|^([\\da-fA-F]{1,4}:){2}((:[\\da-fA-F]{1,4}){1,4}|:)$|^([\\da-fA-F]{1,4}:){3}((:[\\da-fA-F]{1,4}){1,3}|:)$|^([\\da-fA-F]{1,4}:){4}((:[\\da-fA-F]{1,4}){1,2}|:)$|^([\\da-fA-F]{1,4}:){5}:([\\da-fA-F]{1,4})?$|^([\\da-fA-F]{1,4}:){6}:$", RegexOptions.Compiled);
            return false;
        }

        /// <summary>
        /// 返回redis服务器地址
        /// </summary>
        /// <returns></returns>
        public static string WebConfig(string keys)
        {
            return System.Web.Configuration.WebConfigurationManager.AppSettings[$"{keys}"];
        }
    }
}
